package me.eg.second;

import java.util.HashMap;
import java.util.Map;

/**
 * 1074. 元素和为目标值的子矩阵数量
 *
 * https://leetcode-cn.com/problems/number-of-submatrices-that-sum-to-target/
 */
public class NumSubmatrixSumTarget {
    public int numSubmatrixSumTarget(int[][] matrix, int target) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        int[] colSum = new int[cols];
        int ans = 0;
        for (int r1 = 0; r1 < rows; r1++) {
            colSum = matrix[r1];
            // 处理当前行
            ans += subarraySum(colSum, target);
            for (int r2 = r1 + 1; r2 < rows; r2++) {
                for (int c = 0; c < cols; c++) {
                    colSum[c] += matrix[r2][c];
                }
                ans += subarraySum(colSum, target);
            }
        }

        return ans;
    }

    private int subarraySum(int[] nums, int target) {
        Map<Integer, Integer> map =new HashMap<>();
        map.put(0, 1);
        int sum = 0;
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            sum = sum + nums[i];
            ans += map.getOrDefault(sum - target, 0);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        return ans;
    }
}
